package org.ym.database.hibernate.listener;


import org.ym.basic.ContextUtils;
import org.ym.database.hibernate.base.BaseModel;
import org.ym.basic.base.ICurrentUser;

import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.util.Date;

/**
 * @author ym
 */
public class AuditingEntityListener {

    @PrePersist
    public void prePersist(Object entity){
        //insert之前
        if(entity instanceof BaseModel){
            BaseModel baseModel = (BaseModel) entity;
            if(baseModel.getCreateTime() == null) {
                baseModel.setCreateTime(new Date());
            }
            ICurrentUser sysUser = ContextUtils.getCurrentUser();
            if(sysUser != null) {
                baseModel.setCreatedById(sysUser.getUserId());
                baseModel.setCreatedBy(sysUser.getUserName());
            }
        }
    }

    @PostPersist
    public void postPersist(Object entity){
        //insert之后
    }

    @PreUpdate
    public void preUpdate(Object entity){
        //update之前
        if(entity instanceof BaseModel){
            BaseModel baseModel = (BaseModel) entity;
            if(baseModel.getUpdateTime() == null){
                baseModel.setUpdateTime(new Date());
            }
            ICurrentUser sysUser = ContextUtils.getCurrentUser();
            if(sysUser != null) {
                baseModel.setUpdatedById(sysUser.getUserId());
                baseModel.setUpdatedBy(sysUser.getUserName());
            }
        }
    }

    @PostUpdate
    public void postUpdate(Object entity){
        //update 之后
    }
}
